%% 多条多径误差验证
clear
M=6;
SNR=1:0.1:50;
tau_number = rand(1,M);
tau = tau_number * 1;%时延
alapha_number = rand(1,M)*2-1;
alapha = alapha_number * 0.2;%反射系数
%%
d=400;
% 相关距离
for ll=1:length(SNR)
    x=-2:0.001:2;
    y=(x+1).*(x<=0 & x>-1)-(x-1).*(x<1 & x>0);
    y_end=0;
    for ii =1:length(tau)  %遍历各条多路径
        tau1=floor(tau(ii)*1000);
        alapha1=alapha(ii);
        y1=zeros(1,length(y));
        y1(tau1+1:end)=y(1:end-tau1);
        y1(1:tau1)=y(end-tau1+1:end);
        y_end=y_end+alapha1*y1;
    end
    y_end=y_end+y;%生成相关峰
    y_end=awgn(y_end,SNR(ll));
    f=floor(length(y_end)/2)+200;
    m=f-d/2;
    i=f+d/2;
    v_pr=y_end(i);
    v_la=y_end(m);
    p=0;%计算次数
    while abs(v_pr-v_la)>0.005
        if v_pr>v_la
            m=m+1;
            i=i+1;
        end
        if v_pr<v_la
            m=m-1;
            i=i-1;
        end
        v_pr=y_end(i);
        v_la=y_end(m);
        p=p+1;
        if p>5000
            break
        end
    end
    d2=800;
    m2=f-d2/2;
    i2=f+d2/2;
    v_pr2=y_end(i2);
    v_la2=y_end(m2);
    p=0;%计算次数
    while abs(v_pr2-v_la2)>0.005
        if v_pr2>v_la2
            m2=m2+1;
            i2=i2+1;
        end
        if v_pr2<v_la2
            m2=m2-1;
            i2=i2-1;
        end
        v_pr2=y_end(i2);
        v_la2=y_end(m2);
        p=p+1;
        if p>5000
            break
        end
    end

    error_sim=((m2+i2+m+i)/4-length(y_end)/2)/1000;
    error_sim_M(ll)=error_sim;
end
% figure
% plot(x,y_end,'-')
% set(gca,'XLim',[-2 2]);%X轴的数据显示范围
% set(gca,'YLim',[0 1.5]);%X轴的数据显示范围
hold on
plot(SNR,abs(error_sim_M),'-')
xlim([0,50])
%% 天线抖动时的多径误差
for ll=1:length(SNR)
    x=-2:0.001:2;
    y=(x+1).*(x<=0 & x>-1)-(x-1).*(x<1 & x>0);
    y_end=0;
    Q=1000;
    for dd=1:Q
        alapha_number = rand(1,M)*2-1;
        alapha = alapha_number * 0.4;%反射系数
        for ii =1:length(tau)  %遍历各条多路径
            tau1=floor(tau(ii)*1000);
            alapha1=alapha(ii);
            y1=zeros(1,length(y));
            y1(tau1+1:end)=y(1:end-tau1);
            y1(1:tau1)=y(end-tau1+1:end);
            y_end=y_end+alapha1*y1;
        end
        y_end=y_end+y;%生成相关峰
        y_end=awgn(y_end,SNR(ll));
        f=floor(length(y_end)/2)+200;
        m=f-d/2;
        i=f+d/2;
        v_pr=y_end(i);
        v_la=y_end(m);
        p=0;%计算次数
        while abs(v_pr-v_la)>0.005
            if v_pr>v_la
                m=m+1;
                i=i+1;
            end
            if v_pr<v_la
                m=m-1;
                i=i-1;
            end
            v_pr=y_end(i);
            v_la=y_end(m);
            p=p+1;
            if p>5000
                break
            end
        end
        error_sim(dd)=((m+i)/2-length(y_end)/2)/1000;
    end
    error_sim_M(ll)=mean(error_sim);
end
hold on
plot(SNR,abs(error_sim_M),'-')
%%
hold on
xlim([0,50])
ylim([0,0.2])